<?php


namespace App\Cache;


use EasySwoole\RedisPool\RedisPool;

class UserCache
{
    const PREFIX = 'user_cache:';

    protected $redis;

    public function __construct()
    {
        $this->redis = RedisPool::defer();
    }

    public static function token($token)
    {
        return self::PREFIX."token:{$token}";
    }

    public static function userInfo($id)
    {
        return self::PREFIX."user_info:{$id}";
    }


    public function getUserIdByToken($token)
    {
        $redisKey = self::token($token);
        $userId = $this->redis->get($redisKey);
        $userId = (int) $userId;
        if(!$userId){
            return [];
        }
    }

    public function getUserInfoByToken($token)
    {
        $userId = $this->getUserIdByToken($token);
        if(!$userId){
            return [];
        }

        $userInfo = $this->getUserInfoById($userId);
        return $userInfo;
    }


    public function getUserInfoById($userId)
    {
        $redisKey = self::userInfo($userId);
        $userInfo = $this->redis->hgetall($redisKey);
        return $userInfo;
    }


    public function setTokenUserIdCache($userId,$token)
    {
        $redisKey = self::token($token);
        $this->redis->set($redisKey,$userId,300);
        return true;
    }
}